package com.market.plus.controller.validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.market.plus.core.dto.ParticipantDto;
import com.market.plus.core.dto.RelationshipDto;
import com.market.plus.core.service.ParticipantService;

@Component("relationshipValidator")
public class RelationshipValidator implements Validator {

   @Autowired
   private ParticipantService participantService;

   public boolean supports(Class<?> relationship) {
      return RelationshipDto.class.isAssignableFrom(relationship);
   }

   public void validate(Object object, Errors errors) {
      validateRelationship(object, errors, 0);
   }

   public void validateRelationship(Object object, Errors errors, long participantId) {
      RelationshipDto relationship = (RelationshipDto) object;
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "relationName", "err.required");
      if (!errors.hasFieldErrors("relationName")){
         if (participantId == 0){
            ParticipantDto participantDto = this.participantService.findLoginUserName(true);
            participantId = participantDto.getId();
         }
         if (participantService.hasRealtionshipExist(participantId, relationship.getRelationName())){
            errors.rejectValue("relationName", "err.unique");
         }
      }
   }
}
